package com.gang.music.core.exception;

import com.gang.music.common.AjaxResult;
import com.gang.music.core.toolbox.JsonUtils;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 重写SimpleMappingExceptionResolver的doResolveException,
 * 实现对ajax请求发生错误时,返回json数据,普通请求返回错误页面
 * @author Administrator
 *
 */
public class GlobalExceptionResolver extends SimpleMappingExceptionResolver {

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		
		String header = request.getHeader("X-Requested-With");
		boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
		if(!isAjax) {
			return super.doResolveException(request, response, handler, ex);
		}else {
			String errorMsg = "";
			if (ex instanceof MaxUploadSizeExceededException) {
				long maxSize = ((MaxUploadSizeExceededException)ex).getMaxUploadSize();
				errorMsg = "文件不能超过" +maxSize / 1024 / 1024 + "m";
			}else
				errorMsg = ex.getMessage();
			AjaxResult ajaxResult = new AjaxResult();
			ajaxResult.addError(errorMsg);
			try {
				String json = JsonUtils.objectToJson(ajaxResult);
				response.setContentType("application/json; charset=utf-8");
				response.getWriter().write(json);
				response.getWriter().flush();
				response.getWriter().close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
	}
}
